/**
 * 
 */
package com.ben.smm.broadcast;

import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import com.ben.smm.domain.Sms;
import com.ben.smm.util.CheckSms;
import com.ben.smm.util.SmsDBHelper;

/**
 * @author lixuanbin
 */
public class SmsBroadcastReceiver extends BroadcastReceiver {
	public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
	 * android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent != null && SMS_RECEIVED.equalsIgnoreCase(intent.getAction())) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				// Get messages
				Object[] objects = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[objects.length];
				Sms[] smsArray = new Sms[objects.length];
				for (int i = 0; i < objects.length; i++) {
					messages[i] = SmsMessage.createFromPdu((byte[]) objects[i]);
					Sms tempSms = new Sms();
					tempSms.setContent(messages[i].getDisplayMessageBody());
					tempSms.setType("in");// In messages
					tempSms.setPhone_number(messages[i]
							.getDisplayOriginatingAddress());
					tempSms.setSms_date(new Date(messages[i]
							.getTimestampMillis()));
					smsArray[i] = tempSms;
					tempSms = null;
				}

				// Make toast
				StringBuffer stringBuffer = new StringBuffer();
				for (SmsMessage smsMessage : messages) {
					stringBuffer.append("收到来自："
							+ smsMessage.getDisplayOriginatingAddress() + "\n");
					stringBuffer.append("内容为：\n"
							+ smsMessage.getDisplayMessageBody());
				}
				Log.i("smm", stringBuffer.toString());
				Toast.makeText(context, stringBuffer.toString(), 15000);

				// Insert messages
				SmsDBHelper dbHelper = new SmsDBHelper(context);
				for (Sms sms : smsArray) {
					if (CheckSms.isSMMEncryptedSms(sms)) {
						Log.i("smm", String.valueOf(dbHelper.insert(sms)));
					}
				}

				// Close database
				if (dbHelper != null) {
					dbHelper.close();
					dbHelper = null;
				}
			}
		}
	}

}
